package com.ycb.service;

import com.alibaba.nacos.common.utils.DateFormatUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycb.entity.Goods;
import com.ycb.entity.Order;
import com.ycb.feign.GoodsClient;
import com.ycb.feign.UserClient;
import com.ycb.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 黄泽群
 * @since 2023-12-11
 */
@Service
@RequiredArgsConstructor
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    private final UserClient userClient;
    private final GoodsClient goodsClient;

    @GlobalTransactional
    public Order create(Integer userId, Integer goodsId, Integer qty) {
        Goods goods = goodsClient.subStock(goodsId, qty);
        int totalAmt = goods.getPrice() * qty;
        Order order = new Order();
        order.setCode(DateFormatUtils.format(new Date(),DateFormatUtils.YYYYMMDDHHMMSSNOMARK));
        order.setAmt(totalAmt);
        order.setQty(qty);
        order.setGoodsId(goodsId);
        order.setUserId(userId);
        super.save(order);
        userClient.subAmount(userId,totalAmt);
        return order;
    }


}
